<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>购物车</title>
</head>
<body>
	<?php
		header("Content-type:text/html;charset=utf-8");
		include "mysqli.php";

		$a=isset($_GET["a"])?$_GET["a"]:"";
		// 添加购物车
		if($a=="addshoppingcart"){
			$buynum=$_POST["buynum"]; //购买数量
			$id=$_POST["id"]; //商品id

			if(!empty($_COOKIE["shoppingcart"])){
				// unserialize 从已存储的表示中创建 PHP 的值,对单一的已序列化的变量进行操作，将其转换回 PHP 的值
				$shoppingcart=unserialize($_COOKIE["shoppingcart"]);
			}else{
				$shoppingcart=array();
			}
			if(isset($id)&&isset($buynum)){
				// intval 获取变量的整数值
				$id=intval($id);
				$buynum=intval($buynum);
				$shoppingcart[]=array($id,$buynum);
			}

			// 商品属性进行序列化保存到cookie中
			setcookie("shoppingcart",serialize($shoppingcart));
			return "true";

		}else if($a=="buynow"){
			// 展示商品
			if(!empty($_COOKIE["shoppingcart"])){
				?>
			<table border="1">
				<tr bgcolor="#87ceeb">
					<td>商品ID</td>
					<td>商品名称</td>
					<td>购买数量</td>
					<td>价格</td>
					<td>操作</td>
				</tr>
				<?php
					$totalprice=0;
					$shoppingcart=unserialize($_COOKIE["shoppingcart"]);

					foreach($shoppingcart as $key=>$value){
						$key=array($key);
				?>
				<tr>
					<td><?php echo $value[0]?></td>
					<td>
						<?php
						$sql="select *from goods where id=".intval($value[0]);
						$result=$mysqli->query($sql);
						$row=$result->fetch_assoc();
						$totalprice+=$row["salesprice"]*$value[1];
						echo '<a href="goodsshow.php?cid='.$row['goodstypeid'].'&id='.$row['id'].'" class="title" target="_blank">'.$row['title'].'</a>';
						?>
					</td>
					<td><?php echo $value[1]?></td>
					<td><?php echo $row["salesprice"]*$value[1]?></td>
					<td><a href="shoppingcart.php?a=delone&key=<?php echo $key[0] ?>">取消</a></td>
				</tr>
				<?php } ?>

			</table>
			<hr>
			<span>总价格：<?php echo $totalprice ?>
				<a href="">下一步</a>
				<a href="shoppingcart.php?a=empty">清空购物车</a>
			</span>

				<?php
			}

		}else if($a=="delone"){
			// 取消,取消一件商品只需要unset掉对应的key值即可
			$key=$_GET["key"];
			$shoppingcart=unserialize($_COOKIE["shoppingcart"]);
			// unset 释放给定的变量
			unset($shoppingcart[$key]);
			if(empty($_COOKIE)){
				setcookie($shoppingcart,"",time()-3600); //设置cookie过期时间，值为负即已过期
			}else{
				setcookie("shoppingcart",serialize($shoppingcart));
			}
			header("location:shoppingcart.php?a=buynow");
			exit();
		}else if($a=="empty"){
			// 清空购物车,清除整个cookie保存的商品信息
			unset($_COOKIE["shoppingcart"]);
			setcookie("shoppingcart","",time()-3600);
			echo "<div>您的购物车目前没有商品！3秒后跳回首页......</div>";
			header("Refresh:3;url=goods.php");
		}
	?>
</body>
</html>